Checking If A User-Created Filename Is Valid

Last Updated: 1st May

Sometimes you'll want to check if a filename created by the user is valid. The following function tests if a string is valid for use in a filename, not including the file extension:
function IsFileValid(filename : string) : Boolean;
var
  i : integer;
  F : TextFile;
begin
  i := 0;
  if Length(filename) = 0 then begin
    Result := False;
    Exit;
  end; {if}
  Result := True;
  repeat
    inc(i);
    if (filename[i] in ['\','/',':','*','?','"','<','>','|','.']) then
      Result := False;
  until (Result = False) or (i = Length(filename));
  if Result = False then Exit;
  try
    AssignFile(F, filename + '.txt');
    ReWrite(F);
    CloseFile(F);
    DeleteFile(PChar(filename + '.txt'));
  except
    Result := False;
  end; {try}
end; {function}


lonewolf@tig.com.au